﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ContactManager.Common;
using System.Data.OleDb;

namespace ContactManager
{
    public partial class MonthReportFrm : AlSkin.AlForm.AlBaseForm
    {
        int id = 0;

        public MonthReportFrm()
        {
            InitializeComponent();
        }

        private DateTime now = DateTime.Now;

        private void MonthReportFrm_Load(object sender, EventArgs e)
        {
            this.labelContactName.Text = Constant.TITLE + GlobleUser.USER_NAME;
            
            //初始化最近联系人
            this.combRecent.Items.Clear();
            string recentSql = "select top 18 c.c_id,c.c_name,max(t.t_time) from contacters c,traces t where c.c_id = t.t_c_id group by c.c_id,c.c_name order by max(t.t_time) desc";
            DataSet recentDs = AccessHelper.ExecuteQuery(recentSql);
            foreach (DataRow dr in recentDs.Tables[0].Rows)
            {
                ComboBoxItem ci = new ComboBoxItem();
                ci.Text = Convert.ToString(dr["c_name"]);
                ci.Value = dr["c_id"];
                this.combRecent.Items.Add(ci);
            }

            //初始时间
            setDate();

            //初始化控件
            initFormEnable(false);
            this.labReportName.Text = "汇报人：" + this.txtName.Text.Trim();

        }

        private void setDate()
        {
            //初始化ID，表单
            id = 0;
            this.btnReset_Click(this, null);
            //初始化日期
            string firstDay = new DateTime(now.Year, now.Month, 1).ToString("yyyy-MM-dd");
            string lastDay = new DateTime(now.Year, now.Month, 1).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            this.labTimeStart.Text = firstDay;
            this.labTimeEnd.Text = lastDay;
            ListViewItem[] li = new ListViewItem[1];
            li[0] = new ListViewItem(new string[] { firstDay + "~" + lastDay });
            this.listViewDate.Items.Clear();
            this.listViewDate.Items.AddRange(li);
            //添加Imagelist设置Listview行高
            ImageList il = new ImageList();
            il.ImageSize = new Size(1, 25);
            this.listViewDate.SmallImageList = il;

            //判断是否有记录
            string rSql = "select m_id,m_leadname,m_name,m_title,m_department,m_phone,m_mail,m_content,m_next_content from monthreport where m_start_date=#" + firstDay + "# and m_end_date=#" + lastDay + "#";
            DataSet rDs = AccessHelper.ExecuteQuery(rSql);
            if (rDs.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in rDs.Tables[0].Rows)
                {
                    id = Convert.ToInt32(dr[0].ToString());
                    this.txtLeadName.Text = dr[1].ToString();
                    this.txtName.Text = dr[2].ToString();
                    this.txtTitle.Text = dr[3].ToString();
                    this.txtDepartMent.Text = dr[4].ToString();
                    this.txtPhone.Text = dr[5].ToString();
                    this.txtMail.Text = dr[6].ToString();
                    this.txtThisWeekContent.Text = dr[7].ToString();
                    this.txtNextWeekPlan.Text = dr[8].ToString();
                }
            }
            else
            {
                //查找weekreport追踪表
                string sql = "select w_content,w_next_content from weekreport where format(w_start_date,'mm') ='" + now.ToString("MM") + "' or format(w_end_date,'mm')='" + now.ToString("MM") + "'";
                DataSet ds = AccessHelper.ExecuteQuery(sql);
                this.txtThisWeekContent.Clear();
                this.txtNextWeekPlan.Clear();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    this.txtThisWeekContent.Text += dr[0].ToString() + ";";
                    this.txtNextWeekPlan.Text = dr[1].ToString();
                }
            }


            //统计sql
            string sumSql = "select sum(t_deal) as deal,sum(t_income) as income from traces where format(t_time,'yyyy-mm-dd') >=format('" + firstDay + "','yyyy-mm-dd') and format(t_time,'yyyy-mm-dd') <=format('" + lastDay + "','yyyy-mm-dd')";
            DataSet sumDs = AccessHelper.ExecuteQuery(sumSql);
            foreach (DataRow dr in sumDs.Tables[0].Rows)
            {
                string deal = dr[0].ToString();
                string income = dr[1].ToString();
                if (deal.Length == 0)
                {
                    deal = "0";
                }
                if (income.Length == 0)
                {
                    income = "0";
                }
                this.labSum.Text = "本月成交金额为：" + deal + "元 收款金额为：" + income + "元";
            }


            this.labDate.Text = now.Month + "月";

            if (this.txtName.Text.Length == 0)
            {
                this.txtName.Text = GlobleUser.USER_NAME;
            }
        }

        private void combRecent_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBoxItem recent = (ComboBoxItem)this.combRecent.SelectedItem;
            TracesForm tf = new TracesForm(recent.Value.ToString());
            tf.ShowDialog();
        }

        private void btnPreviousWeek_Click(object sender, EventArgs e)
        {
            now = now.AddMonths(-1);
            setDate();
            initFormEnable(false);
        }

        private void btnNextWeek_Click(object sender, EventArgs e)
        {
            if (now < DateTime.Now.AddMonths(-1))
            {
                now = now.AddMonths(1);
                setDate();
                initFormEnable(false);
            }
        }

        private void btnNow_Click(object sender, EventArgs e)
        {
            now = DateTime.Now;
            setDate();
        }

        private void initFormEnable(bool flag)
        {
            this.txtLeadName.Enabled = flag;
            this.txtDepartMent.Enabled = flag;
            this.txtMail.Enabled = flag;
            this.txtName.Enabled = flag;
            this.txtNextWeekPlan.Enabled = flag;
            this.txtPhone.Enabled = flag;
            this.txtThisWeekContent.Enabled = flag;
            this.txtTitle.Enabled = flag;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            initFormEnable(true);
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            this.labReportName.Text = "汇报人：" + this.txtName.Text.Trim();
        }

        private void MonthReportFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("您确定要退出吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
            {
                HomeFrm.mrf = null;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string leadname = this.txtLeadName.Text.Trim();
            string name = this.txtName.Text.Trim();
            string title = this.txtTitle.Text.Trim();
            string department = this.txtDepartMent.Text.Trim();
            string phone = this.txtPhone.Text.Trim();
            string mail = this.txtMail.Text.Trim();
            string content = this.txtThisWeekContent.Text.Trim();
            string nextContent = this.txtNextWeekPlan.Text.Trim();

            if (id == 0)
            {
                string saveSql = "insert into monthreport(m_leadname,m_name,m_title,m_department,m_phone,m_mail,m_content,m_next_content,m_start_date,m_end_date) values(?,?,?,?,?,?,?,?,#" + Convert.ToDateTime(this.labTimeStart.Text).ToString("yyyy/MM/dd") + "#,#" + Convert.ToDateTime(this.labTimeEnd.Text).ToString("yyyy/MM/dd") + "#)";
                OleDbParameter[] ps = {new OleDbParameter("@m_leadname",leadname),
                                       new OleDbParameter("@m_name",name),
                                       new OleDbParameter("@m_title",title),
                                       new OleDbParameter("@m_department",department),
                                       new OleDbParameter("@m_phone",phone),
                                       new OleDbParameter("@m_mail",mail),
                                       new OleDbParameter("@m_content",content),
                                       new OleDbParameter("@m_next_content",nextContent)
                                      };
                if (AccessHelper.ExecuteNonQuery(saveSql, ps) > 0)
                {
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("保存失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (id > 0)
            {
                string updateSql = "update monthreport set m_leadname=?,m_name=?,m_title=?,m_department=?,m_phone=?,m_mail=?,m_content=?,m_next_content=? where m_id=?";
                OleDbParameter[] ps = {new OleDbParameter("@m_leadname",leadname),
                                       new OleDbParameter("@m_name",name),
                                       new OleDbParameter("@m_title",title),
                                       new OleDbParameter("@m_department",department),
                                       new OleDbParameter("@m_phone",phone),
                                       new OleDbParameter("@m_mail",mail),
                                       new OleDbParameter("@m_content",content),
                                       new OleDbParameter("@m_next_content",nextContent),
                                       new OleDbParameter("@m_id",id)
                                      };
                if (AccessHelper.ExecuteNonQuery(updateSql, ps) > 0)
                {
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("保存失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("程序初始化错误,请重启程序", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            MonthReportFrm_Load(this, null);
           
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            this.txtLeadName.Clear();
            this.txtName.Clear();
            this.txtTitle.Clear();
            this.txtDepartMent.Clear();
            this.txtPhone.Clear();
            this.txtMail.Clear();

            this.btnEdit_Click(this, null);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {

            object[] bmarks = { "标题", "领导名", "时间", "姓名", "职位", "部门", "联系方式", "邮件", "日期", "本周", "下周", "统计", "汇报人" };
            string[] values = {
                                this.labMainTitle.Text,
                                this.txtLeadName.Text.Trim(),
                                this.labTimeStart.Text + "~" + this.labTimeEnd.Text,
                                this.txtName.Text.Trim(),
                                this.txtTitle.Text.Trim(),
                                this.txtDepartMent.Text.Trim(),
                                this.txtPhone.Text.Trim(),
                                this.txtMail.Text.Trim(),
                                this.listViewDate.Items[0].SubItems[0].Text,
                                this.txtThisWeekContent.Text.Trim(),
                                this.txtNextWeekPlan.Text.Trim(),
                                this.labSum.Text,
                                this.txtName.Text.Trim()
                            };
            WordUtil.exportWord(bmarks, values, "m.doc");
        }

    }
}
